import api from '../../api/socket';

export const SET_USERNAME = 'set username';
export const SET_KEY = 'set key';

const _state = {
    userName: null,
    key: null
}

export function personInfo(state = _state, action) {
    switch (action.type) {
        case SET_USERNAME:
            return {
                ...state,
                userName: action.userName
            };
        case SET_KEY:
            return {
                ...state,
                key: action.key
            };
        default:
            return {
                ...state
            };
    }
}

//设置用户名称 
export function setUserName(userName) {
    return {
        type: SET_USERNAME,
        userName: userName
    }

}

/**
 * 唯一标识码.
 * @param {String} key 
 */
export function setKey(key) {
    console.log('设置唯一值' + key);
    return {
        type: SET_KEY,
        key: key
    }
}

export function logintest(username) {
    api.login(username);
    return setUserName(username);
}

export function login(userName) {
    return dispatch => {
        api.login(userName, rst => {
            if (rst.code === 1) {
                dispatch(setUserName(userName));
                api.setItem('name', userName);
                // dispatch(setKey(userName));
            } else {
                //登录失败
                console.log('登录失败');
            }
        });
    }
}

export function logout() {
    return dispatch => {
        api.logOut(rst => [
            dispatch(setUserName(null))
        ]);
    }
}